package demo;

import java.util.Arrays;

/**
 * @Author liangzai
 * @Description:
 */
public class Training {
    //统计公平数对的数目
    public long countFairPairs(int[] nums, int lower, int upper) {
        int n=nums.length;
        long ans=0;
        Arrays.sort(nums);
        for(int i=0;i<n-1;i++){
            if(nums[i]+nums[n-1]<lower)continue;
            if(nums[i]+nums[i+1]>upper)break;
            int l=i+1,r=n-1;
            while(l<r){
                int mid=(l+r)/2;
                if(nums[i]+nums[mid]>=lower)r=mid;
                else l=mid+1;
            }
            int temp=l;
            l=i+1;
            r=n-1;
            while(l<r){
                int mid=(l+r+1)/2;
                if(nums[i]+nums[mid]<=upper)l=mid;
                else r=mid-1;
            }
            ans+=(l-temp+1);
        }
        return ans;
    }
}
